package com.qyhl.shop.shop.center.coupon;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.shop.shop.center.shop.ShopCenterShopListActivity;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopCenterCouponBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopCouponBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ShopCenterCouponListFragment extends BaseFragment implements ShopCenterCouponListContract.ShopCenterCouponListView {
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private int type;//1 待使用, 2 已使用, 3 已过期

    private CommonAdapter<ShopCenterCouponBean> commonAdapter;

    private List<ShopCenterCouponBean> mDataList = new ArrayList<>();

    private int page = 1;

    private ShopCenterCouponListPresenter mPresenter;

    public void setType(int type) {
        this.type = type;
    }

    public static ShopCenterCouponListFragment newInstance(int type) {
        ShopCenterCouponListFragment fragment = new ShopCenterCouponListFragment();
        fragment.setType(type);
        return fragment;
    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();
    }

    @SuppressLint("InflateParams")
    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.shop_fragment_center_coupon, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);


        mPresenter = new ShopCenterCouponListPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<ShopCenterCouponBean>(getContext(), R.layout.shop_item_center_coupon, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopCenterCouponBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopCenterCouponListFragment.this)
                        .load(bean.getImageUrl())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getName());

                holder.setText(R.id.address, bean.getAddress());

                holder.setText(R.id.contact, bean.getPhone());

                holder.setOnClickListener(R.id.shop_enter_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ARouter.getInstance()
                                .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                                .withInt("shopId", bean.getId())
                                .navigation();

                        ActionLogUtils.getInstance().onEvent(ActionConstant.SHOP_FROM_COUPON, bean.getId());
                    }
                });

                RecyclerView recyclerView = holder.getView(R.id.recycler_view);

                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

                List<ShopCouponBean> couponBeans = new ArrayList<>();

                if (bean.getShopCouponDtoList() != null && bean.getShopCouponDtoList().size() > 0) {
                    recyclerView.setVisibility(View.VISIBLE);

                    couponBeans.addAll(bean.getShopCouponDtoList());

                    CommonAdapter<ShopCouponBean> couponCommonAdapter;

                    recyclerView.setAdapter(couponCommonAdapter = new CommonAdapter<ShopCouponBean>(getContext(), R.layout.shop_item_center_coupon_item, couponBeans) {

                        @Override
                        protected void convert(ViewHolder holder, ShopCouponBean couponBean, int position) {
                            holder.setText(R.id.coupon_name, "仅在" + bean.getName() + "使用");

                            holder.setText(R.id.date, "有效期：" + couponBean.getBeginTime() + " ~ " + couponBean.getEndTime());

                            if (couponBean.getType() == 1) {
                                holder.setVisible(R.id.tag, false);
                                holder.setVisible(R.id.tag2, true);
                                holder.setText(R.id.coupon_value, (couponBean.getDiscount() == 0 ? 10 : couponBean.getDiscount()) + "");
                            } else {
                                holder.setVisible(R.id.tag2, false);
                                holder.setVisible(R.id.tag, true);
                                holder.setText(R.id.coupon_value, couponBean.getReduction() + "");
                            }


                            if (couponBean.getThreshold() == 0) {
                                holder.setText(R.id.coupon_limit, "无门槛");
                            } else {
                                holder.setText(R.id.coupon_limit, "满" + couponBean.getThreshold() + "可用");
                            }

                            TextView typeBtn = holder.getView(R.id.type_btn);
                            switch (type) {
                                case 1:
                                    typeBtn.setEnabled(true);
                                    holder.setBackgroundRes(R.id.shop_coupon_end_layout, R.drawable.shop_coupon_adv_end_bg);
                                    typeBtn.setText("立即使用");
                                    break;
                                case 2:
                                    typeBtn.setEnabled(false);
                                    holder.setBackgroundRes(R.id.shop_coupon_end_layout, R.drawable.shop_coupon_end_bg_used);
                                    typeBtn.setText("已使用");
                                    break;
                                case 3:
                                    typeBtn.setEnabled(false);
                                    holder.setBackgroundRes(R.id.shop_coupon_end_layout, R.drawable.shop_coupon_end_bg_exceed);
                                    typeBtn.setText("已过期");
                                    break;
                            }
                        }
                    });

                    couponCommonAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.SHOP_CENTER_COUPON_DETAIL)
                                    .withInt("couponId", couponBeans.get(i).getUserCouponId())
                                    .navigation();
                        }

                        @Override
                        public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            return false;
                        }
                    });
                } else {
                    recyclerView.setVisibility(View.GONE);
                }


            }
        });

        mPresenter.getList(type, page, CommonUtils.getInstance().getUserName());
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getList(type, page, CommonUtils.getInstance().getUserName());
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getList(type, page, CommonUtils.getInstance().getUserName());
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(type, page, CommonUtils.getInstance().getUserName());
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setList(List<ShopCenterCouponBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (beanList == null) {
            setError("暂无任何优惠券!");
            return;
        }
        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                showToast(msg);
            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }
}
